<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
		</style>
	</head>
	<body>
		<!-- <input type="file" > -->
		<canvas id="canvas"></canvas>
		<img id="outImg" src="" alt="">
		<script type="text/javascript">
			const canvas = document.querySelector("#canvas");
			const ctx = canvas.getContext("2d");
			canvas.width = document.documentElement.clientWidth - 50; //网页可见区域宽
			canvas.height = document.documentElement.clientHeight - 100; //网页可见区域高
			
			const img = new Image();
			img.src = "../image/bg.jpg";
			img.onload = () => {
				drawimg();
			}
			function drawimg() {
				ctx.fillStyle = ctx.createPattern(img, "repeat");
				ctx.fillRect(0, 0, canvas.width, canvas.height);
			}
			let painting = false;
			let darwPoints = [];
			let wh = [];
			
			canvas.addEventListener("mousedown", (e) => {
				painting = true;
				darwPoints = [e.offsetX, e.offsetY];
			});
			canvas.addEventListener("mousemove", (e) => {
				if (!painting) return;
				ctx.clearRect(0, 0, canvas.width, canvas.height);
				const [x, y] = darwPoints;
				const w = e.offsetX - x;
				const h = e.offsetY - y;
				drawimg();
				ctx.strokeRect(x, y, w, h);
				wh = [w, h];
			});
			canvas.addEventListener("mouseup", () => {
				painting = false;
				const [x, y] = darwPoints; 
				const [w, h] = wh; 
				const imgData = ctx.getImageData(x, y, w, h);
				const cvs = document.createElement('canvas');
				const _ctx = cvs.getContext('2d');
				cvs.width = w;
				cvs.height = h;
				_ctx.putImageData(imgData, 0, 0);
				outImg.src = cvs.toDataURL();
			});
		</script>
	</body>
</html>